﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessRule.BusinessFactory;
using BusinessRule.IBusiness;
using BusinessRule.DTO;
using DatabaseAccess.DBUtility;
using System.Collections;
using System.Data;

public partial class forms_Custom_my_FillSubContainerProduceForm : System.Web.UI.Page
{
    private bool isTrans = false;
    private uLMSContainercurrentinfoIBusiness m_Concurrentinfo = uMESBusinessFactory.instance.GetuLMSContainerCurrentInfoObject();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtContainerName.ClearData();
            txtCheckDate.ClearData();
            txtReportDate.ClearData();
            ShowMessage(true, "");
        }
    }
    /// <summary>
    /// 处理子卡异常导致的问题
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <remarks>如：1、热表子卡工步全部检验完成，但未入库且没有工序检验。2、热表子卡干完，但是主制工序未有自动报工数据</remarks>
    protected void btnFillStepProduce_Click(object sender, EventArgs e)
    {
        try
        {
            ShowMessage(true, "");
            string containerName = txtContainerName.Data.ToString();
            if (string.IsNullOrWhiteSpace(containerName))
            {
                ShowMessage(false, "请输入批次");
                return;
            }
            uMESProcessResult res = m_Concurrentinfo.DealSubContainerError(containerName);
            if (res.Result && res.ReturnData != null)
            {
                Dictionary<string, string> dic = (Dictionary<string, string>)res.ReturnData;
                txtReportDate.Data = dic["ReportDate"];
                txtCheckDate.Data = dic["CheckDate"];
                txtContainerID.Data = dic["ContainerID"];
                txtWorkflowStepID.Data = dic["WorkflowstepID"];
            }
            ShowMessage(res.Result, res.Message);
        }
        catch (Exception ex)
        {
            ShowMessage(false, "出错，原因：" + ex.Message);
        }
    }

    /// <summary>
    /// 修改日期
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnEditDate_Click(object sender, EventArgs e)
    {
        try
        {
            ShowMessage(true, "");
            string reportDate = txtReportDate.Data.ToString();
            string checkDate = txtCheckDate.Data.ToString();
            string containerID = txtContainerID.Data.ToString();
            string workflowStepID = txtWorkflowStepID.Data.ToString();
            if (string.IsNullOrWhiteSpace(reportDate) && string.IsNullOrWhiteSpace(checkDate))
            {
                ShowMessage(false, "没有报工、检验日期");
                return;
            }
            string sql = string.Format(@"SELECT 1 FROM containersteprecord csr WHERE csr.containerid = '{0}' AND csr.workflowstepid = '{1}' 
                                     AND csr.usefulstatus = 0 AND csr.checkdate IS NOT NULL", containerID, workflowStepID);
            if (DatabaseHelper.GetSingle(sql) == null)
            {
                ShowMessage(false, "结转服务还未结转，请稍等再试");
                return;
            }
            ArrayList list = new ArrayList();
            //更新报工总表
            sql = string.Format(@"UPDATE containersteprecord csr SET csr.checkdate = to_date('{0}','yyyy-MM-dd hh24:mi:ss'),
                                csr.reportdate=to_date('{1}','yyyy-MM-dd hh24:mi:ss') WHERE csr.containerid = '{2}' AND csr.workflowstepid = '{3}'"
                                , checkDate, reportDate, containerID, workflowStepID);
            list.Add(sql);
            //更新报工
            sql = string.Format(@"UPDATE containerstepworkreport csw SET csw.createdate = to_date('{0}','yyyy-MM-dd hh24:mi:ss')
                                WHERE csw.containerid = '{1}' AND csw.workflowstepid = '{2}' AND csw.isuse = 0"
                                , reportDate, containerID, workflowStepID);
            list.Add(sql);
            //更新检验
            sql = string.Format(@"UPDATE containercheckinfo cci SET cci.createdate = to_date('{0}','yyyy-MM-dd hh24:mi:ss')
                                  WHERE cci.containerid = '{1}' AND cci.workflowstepid = '{2}' AND cci.isuse = 0"
                                , checkDate, containerID, workflowStepID);
            list.Add(sql);
            DatabaseHelper.ExecuteSqlTran(list);
            txtCheckDate.ClearData();
            txtReportDate.ClearData();
            txtWorkflowStepID.ClearData();
            txtContainerID.ClearData();
            ShowMessage(true, "修改成功");
        }
        catch (Exception ex)
        {
            ShowMessage(false, "报错：" + ex.Message);
        }
    }

    /// <summary>
    /// 显示消息
    /// </summary>
    /// <param name="res"></param>
    /// <param name="message"></param>
    private void ShowMessage(bool res, string message)
    {
        if (res)
        {
            showMessage.Style["color"] = "black";
        }
        else
        {
            showMessage.Style["color"] = "red";
        }
        showMessage.InnerText = message;
    }
    /// <summary>
    /// 获取子卡的报工、检验日期
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnGetRecordDate_Click(object sender, EventArgs e)
    {
        ShowMessage(true, "");
        string containerName = txtContainerName.Data.ToString();
        if (string.IsNullOrWhiteSpace(containerName))
        {
            ShowMessage(false, "请输入批次");
            return;
        }
        string sql = string.Format(@"SELECT DISTINCT c.containerid,c.containername,c.workflowstepid,c.qty,
                                cc.containerid subcontainerid,cc.containername subcontainername,cc.isinstore,cc.containerstatus 
                                FROM containercurrentinfo c
                                LEFT JOIN containersubcontainer csc ON csc.containerid = c.containerid AND (csc.workflowstepid = c.workflowstepid OR csc.workflowstepname = c.workflowstepname)
                                LEFT JOIN containercurrentinfo cc ON cc.containerid = csc.subcontainerid
                                WHERE c.containername = '{0}' AND c.containerstatus = 1 AND c.isinstore = 0", containerName);
        DataTable dtContainer = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtContainer.Rows.Count == 0)
        {
            ShowMessage(false, "批次未在制");
            return;
        }
        if (dtContainer.AsEnumerable().Where(p => string.IsNullOrWhiteSpace(p["subcontainerid"].ToString())).Count() > 0)
        {
            ShowMessage(false, "批次当前序不存在子卡");
            return;
        }
        if (dtContainer.AsEnumerable().Where(p => p["isinstore"].ToString() != "1" || p["containerstatus"].ToString() != "1").Count() > 0)
        {
            ShowMessage(false, "批次子卡未完工或者状态无效");
            return;
        }
        sql = string.Format("SELECT 1 FROM containercheckinfo cci WHERE cci.containerid = '{0}' AND cci.workflowstepid = '{1}' AND cci.isuse = 0", dtContainer.Rows[0]["ContainerID"].ToString(), dtContainer.Rows[0]["WorkflowstepID"].ToString());
        if (DatabaseHelper.GetSingle(sql) == null)
        {
            ShowMessage(false, "批次在制工序不存在检验");
            return;
        }
        sql = string.Format(@"SELECT to_char(csr.checkdate,'yyyy-MM-dd hh24:mi:ss') checkdate,
                to_char(csr.reportdate,'yyyy-MM-dd hh24:mi:ss') reportdate
                FROM containersteprecord csr 
                left JOIN workflowstep ws ON ws.workflowstepid = csr.workflowstepid
                WHERE csr.containerid = '{0}' AND csr.usefulstatus = '1' AND csr.usecompleted = '1' 
                ORDER BY ws.sequence DESC,csr.createdate DESC", dtContainer.Rows[0]["subcontainerid"].ToString());
        DataTable dtStep = DatabaseHelper.Query_ReturnDatTable(sql);
        txtReportDate.Data = dtStep.Rows[0]["ReportDate"].ToString();
        txtCheckDate.Data = dtStep.Rows[0]["CheckDate"].ToString();
        txtContainerID.Data = dtContainer.Rows[0]["ContainerID"].ToString();
        txtWorkflowStepID.Data = dtContainer.Rows[0]["WorkflowstepID"].ToString();
    }
    /// <summary>
    /// 替换机型
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnPf_Click(object sender, EventArgs e)
    {
        string olds = txtOldProductFamily.Data.ToString();
        string news = txtNewProductFamily.Data.ToString();
        string sql = string.Format("SELECT c.mfgbatch,c.containerid FROM CONTAINER C WHERE c.mfgbatch LIKE '%{0}%'", olds);
        DataTable dtPf = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataRow item in dtPf.Rows)
        {
            string mfgbatch = "型别：";
            string[] str = item["mfgbatch"].ToString().Replace("型别：", "").Split(' ');
            foreach (string ss in str)
            {
                if (ss == olds)
                {
                    mfgbatch += news + " ";
                    continue;
                }
                mfgbatch += ss + " ";
            }
            mfgbatch = mfgbatch.TrimEnd();
            DatabaseHelper.ExecuteSql(string.Format("UPDATE container c SET c.mfgbatch = '{0}' WHERE c.containerid = '{1}'", mfgbatch, item["containerid"].ToString()));
        }
        sql = string.Format("SELECT CC.familylistnames,CC.containerid FROM containercurrentinfo CC WHERE CC.familylistnames LIKE '%{0}%' ", olds);
        DataTable dtPf1 = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataRow item1 in dtPf1.Rows)
        {
            string mfgbatch = "";
            string[] str = item1["familylistnames"].ToString().Split(' ');
            foreach (string ss in str)
            {
                if (ss == olds)
                {
                    mfgbatch += news + " ";
                    continue;
                }
                mfgbatch += ss + " ";
            }
            mfgbatch = mfgbatch.TrimEnd();
            DatabaseHelper.ExecuteSql(string.Format("UPDATE containercurrentinfo c SET c.familylistnames = '{0}' WHERE c.containerid = '{1}'", mfgbatch, item1["containerid"].ToString()));
        }
    }
}